<template>
  <div>
    <NuxtLayout name="backgroud">
      <div class="reset">
        <div class="reset_form">
          <p class="kaiti">{{ title }}</p>
          <el-form
            v-if="title == '修改密码'"
            ref="formPassRef"
            label-position="top"
            label-width="100px"
            :model="formPass"
            :rules="passRules"
          >
            <el-form-item prop="passWord" label="新密码：">
              <el-input v-model="formPass.passWord" />
            </el-form-item>
          </el-form>
          <el-form
            v-if="title == '修改资料'"
            ref="formInfoRef"
            label-position="left"
            label-width="80px"
            :model="formInfo"
            :rules="infoRules"
          >
            <el-form-item prop="mail" label="邮箱：">
              <el-input v-model="formInfo.mail" />
            </el-form-item>
            <el-form-item prop="phone" label="电话：">
              <el-input v-model="formInfo.phone" />
            </el-form-item>
            <el-form-item prop="avatar" label="头像：">
              <el-upload
                class="avatar-uploader"
                action="/api/upload"
                :show-file-list="false"
                :limit="1"
                :headers="headers"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <i v-else class="iconfont icon-xinzeng1 avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-form>
          <div class="reset_form-button">
            <el-button type="primary" @click="submitForm(type == 'editPass'?formPassRef:formInfoRef)">
              提 交
            </el-button>
            <el-button @click="resetForm(type == 'editPass'?formPassRef:formInfoRef)">
              取 消
            </el-button>
          </div>
        </div>
      </div>
    </NuxtLayout>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, FormInstance, FormRules,UploadProps  } from 'element-plus'
import { ref, reactive } from 'vue';
import { useRoute } from 'vue-router';
import { resetPassWord,editUserInfo } from "../../service/api/Blogger"
const route = useRoute();
let title = ref(route.query.title)
let type = ref(route.query.type)
const userInfo = ref()
const formPassRef = ref()
const formInfoRef = ref()
const formPass = reactive({
  passWord:'',
  userName:''
})
let formInfo = reactive({
  mail:'',
  phone:'',
  avatar:'',
  userName:''
})
const imageUrl = ref('')
const headers = reactive({
  // 'content-type':'application/multipart/form-data'
})
const passRules = reactive({
  passWord:[
    { required: true, message: '请输入新密码', trigger: 'blur' },
  ]
})
const infoRules = reactive({
  mail:[
    { required: true, message: '请输入邮箱', trigger: 'blur' },
  ],
  phone:[
    { required: true, message: '请输入电话', trigger: 'blur' },
  ]
})
//上传头像
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  formInfo.avatar = 'http://www.lihynotes.cn:81/upload/' + response.data.newFilename
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 1) {
    ElMessage.error('图片尺寸不能超过 1MB!')
    return false
  }
  return true
}
//提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if(title.value == '修改密码'){
        resetPassWord(formPass).then((res:any) => {
          let data = res.data._rawValue
          if(data.code == 200){
            ElMessage({
              message: data.message,
              type: 'success',
            })
            localStorage.removeItem('userInfo')
            userInfo.value = JSON.parse(localStorage.getItem('userInfo'))
          } else {
            ElMessage.error(data.message)
          }
        })
      }
      if(title.value == '修改资料'){
        editUserInfo(formInfo).then((res:any) => {
          let data = res.data._rawValue
          if(data.code == 200){
            ElMessage({
              message: data.message,
              type: 'success',
            })
            localStorage.removeItem('userInfo')
            userInfo.value = JSON.parse(localStorage.getItem('userInfo'))
          } else {
            ElMessage.error(data.message)
          }
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  navigateTo({
    path:'/'
  })
}
onMounted(() => {
  // if(process.client){
    let userInfo = JSON.parse(localStorage.getItem('userInfo'))
    console.log(userInfo)
    formPass.userName = userInfo?.userName
    formInfo.userName = userInfo?.userName
    formInfo.mail = userInfo?.mail
    formInfo.phone = userInfo?.phone
    formInfo.avatar = userInfo?.avatar
    imageUrl.value = userInfo?.avatar
  // }
})
</script>

<style scoped lang="scss">
.reset{
  width: 80%;
  margin: 60px auto;
  height: calc(100vh - 320px);
  display: flex;
  justify-content: center;
  align-items: center;
  &_form{
    width: 300px;
    padding: 20px;
    background-color: rgba(225, 225, 225, .8);
    border-radius: 4px;
    p{
      font-size: 20px;
      text-align: center;
      margin-bottom: 10px;
    }
    &-button{
      margin-top: 20px;
      text-align: center;
    }
  }
}
</style>